<?php

namespace Modules\Car\Http\Controllers;

use App\Helpers\ResponseData;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Modules\Car\Entities\RecognizeDrivingLicense;
use Modules\Car\Http\Requests\RecognizeDrivingRequest;
use Modules\Car\Entities\CarOrder;
use Modules\Car\Entities\Service;
use Modules\Car\Entities\Maintenance;
use App\Models\Car\CarCost;
use App\Models\InsureLogs;

//驾驶证
class DrivingController extends Controller
{
    use ResponseData;
    public function list(RecognizeDrivingLicense $license,Request $request){
        $size = $request->input('size',10);
        $model = $license
            ->with(['waittingService'=>function($query){
                $query->select('id','is_custom','car_id','status','outage_rate','outage_cost','need_start','order_sn')->whereIn('status',[2,3]);
            },'carSeries','useOrders'=>function($query){
                $query->select('id','gear_car_id','order_sn','department')->where('status',5)->whereIn('process_status',[1,2]);
            }])
            ->select('cars.id as car_id','cars.name as car_name','cars.base_price as car_base_price','cars.brokerage as car_brokerage','cars.minimum_price as car_minimum_price','recognize_driving_licenses.*')
            ->join('cars','recognize_driving_licenses.car_series_id','=','cars.id');

        if($request->filled('minimum_price')){

            if($request->minimum_price==1){
                $model = $model->orderBy('cars.total_price');
            }else{
                $model = $model->orderBy('cars.total_price','desc');
            }

        }
        if($request->filled('bind_user_names')){
            $model = $model->where('bind_user_names','like','%'.$request->bind_user_names.'%');

        }
        // 只搜数字
        if($request->filled('search')){
//            $model = $model->where('recognize_driving_licenses.plate_number','like','%'.$request->search.'%')
//                ->orWhere('recognize_driving_licenses.gear_car_name','like','%'.$request->search.'%');
            $model = $model->where(function($query)use($request){
                $query->where('recognize_driving_licenses.plate_number','like','%'.$request->search.'%')
                    ->orWhere('recognize_driving_licenses.gear_car_name','like','%'.$request->search.'%')
                    ->orWhereRaw('REGEXP_REPLACE(recognize_driving_licenses.plate_number, "[^0-9]", "") like "%'.$request->search.'%"');
            });
        }

        //是否在租
        if($request->filled('is_used')){
            $model = $model->where('recognize_driving_licenses.status','!=','-1');
            // 如果是查询的待租车辆，需要去订单里取出所有待送达和待取回车辆，租期之外的在租车辆也需要返回给前端使用能出车的
            if($request->filled('start')&&$request->is_used==0){
                // 先取出所有在租的车辆ID
                $usedCarLists = RecognizeDrivingLicense::query()->whereNull('deleted_at')->where('is_used', 1)->pluck('id');
                // $usedCarLists = $usedCarLists->unique(); // 去重
                // info('$usedCarLists:'.$usedCarLists);
                // $testssss = CarOrder::query()->where('status',5)->whereIn('process_status',[1,2])->where('pre_return_time','<',$request->start)->whereIn('gear_car_id',$usedCarLists)->get();
                // info('$testssss:'.$testssss);
                // 取出所有在租订单（待送达和待取回）
                $usedCars = [];
                $usedCarsAll = [];
                $usedOrders = CarOrder::query()->where('status',5)->whereIn('process_status',[1,2])->whereIn('gear_car_id',$usedCarLists)->get();//->pluck('gear_car_id');
                // 把所有订单的车辆ID和预取回存在字段里
                foreach ($usedOrders as $orderitem){
                    $columnValues = array_column($usedCarsAll, 'gear_car_id'); // 获取所有的值
                    $keys = array_search($orderitem->gear_car_id, $columnValues);
                    if($keys !== false){
                        $usedCarsAll[$keys]['timelist'][] = $orderitem->pre_return_time;
                    }else{
                        $usedCarsAll[] = [
                            'gear_car_id'=>$orderitem->gear_car_id,
                            'timelist'=>[$orderitem->pre_return_time]
                        ];
                    }
                }
                // info($usedCarsAll);
                // 反转数据，只保留重复项的最后一个
                // $usedCarsAllRes = array_reverse($usedCarsAll);
                // $usedCarsSingle = $this->array_unique_by_value($usedCarsAllRes,'gear_car_id');
                foreach ($usedCarsAll as $caritem){
                    // 取时间判断
                    if($this->array_is_all_out($caritem['timelist'],$request->start)){
                        $usedCars[] = $caritem['gear_car_id'];
                    }
                }
                // info($usedCarsSingle);
                // $usedCars = $usedCars->unique(); // 去重
                // info('$usedCars:'.json_encode($usedCars));
                if(count($usedCars)>0){
                    // $model = $model->where('recognize_driving_licenses.is_used',$request->is_used)->orWhereIn('recognize_driving_licenses.id', $usedCars);
                    $model = $model->where(function ($query) use($usedCars) {
                        $query->where('recognize_driving_licenses.is_used',0)->orWhereIn('recognize_driving_licenses.id',$usedCars);
                    });
                }else{
                    $model = $model->where('recognize_driving_licenses.is_used',$request->is_used);
                }
            }else{
                $model = $model->where('recognize_driving_licenses.is_used',$request->is_used);
            }
        }
        //租车状态
        if($request->filled('use_status')){
            if($request->use_status==2){
                $model = $model->where(function ($query) use($request) {
                    $query->where('recognize_driving_licenses.use_status',$request->use_status)->orWhere('recognize_driving_licenses.repair_status','!=',1);
                });
            }else{
                $model = $model->where('recognize_driving_licenses.use_status',$request->use_status);
            }
        }
        if($request->filled('category')&&$request->category!='全部'&&$request->category!='全部车型'){
            $model = $model->where('recognize_driving_licenses.category',$request->category);
        }
        if($request->filled('status')){
            $model = $model->where('recognize_driving_licenses.status',$request->status);
        }
        if($request->filled('ninety')){
            $ninety = $this->getNinety();
            $fortyFave = $this->getFortyFive();
            if($request->ninety==1){
                $model->where('recognize_driving_licenses.vci_end','<',$fortyFave)->orWhereNull('recognize_driving_licenses.vci_end')->orderBy('recognize_driving_licenses.vci_end','asc');
            }elseif($request->ninety==2){
                $model->where('recognize_driving_licenses.mots_end','<',$ninety)->orWhereNull('recognize_driving_licenses.mots_end')->orderBy('recognize_driving_licenses.mots_end','asc');
            }elseif($request->ninety==3){
                $model->where('recognize_driving_licenses.service_end','<',$ninety)->orderBy('recognize_driving_licenses.service_end','asc');
            }elseif($request->ninety==4){
                $model->where('recognize_driving_licenses.tci_end','<',$fortyFave)->orWhereNull('recognize_driving_licenses.tci_end')->orderBy('recognize_driving_licenses.tci_end','asc');
            }
        }elseif($request->filled('recent')){
            if($request->recent==1){
                $model->where('recognize_driving_licenses.vci_end','>',now())->orderBy('recognize_driving_licenses.vci_end','asc');
            }elseif ($request->recent==2){
                $model->where('recognize_driving_licenses.mots_end','>',now())->orderBy('recognize_driving_licenses.mots_end','asc');
            }elseif($request->recent==3){
                $model
                    ->where('distance_kilo_mileage','<','1500')
                    ->orderBy('recognize_driving_licenses.service_end','asc');
            }elseif ($request->recent==4){
                $model->where('recognize_driving_licenses.tci_end','>',now())->orderBy('recognize_driving_licenses.tci_end','asc');
            }
        }
        if($request->filled('car_series_id')){
            $model = $model->where('car_series_id',$request->car_series_id);
        }
//        $model = $model->whereNull('deleted_at');
        $data = $model->paginate($size);
        return $this->success($data);
    }
    // 判断某个值是否都在数组值之外（时间判断）
    protected function array_is_all_out($array, $values) {
        $isout = true;
        foreach ($array as $value) {
            // 只要有一个数组里的时间比比较值大，就false
            if (strtotime($value)>=strtotime($values)) {
                $isout = false;
            }
        }
        return $isout;
    }
    // php 数组根据某个值去重
    protected function array_unique_by_value($array, $key) {
        $unique = array();
        foreach ($array as $value) {
            if (!array_key_exists($key, $value)) {
                throw new InvalidArgumentException('The provided array does not have the specified key');
            }
            if (!array_key_exists($value[$key], $unique)) {
                $unique[$value[$key]] = $value;
            }
        }
        return array_values($unique);
    }
    //获取90天日期
    protected function getNinety(){
       $start =  date("Y-m-d H:i:s",strtotime("+90 day"));
       return $start;
//       return [now(),$start];
    }
    //获取45天日期
    protected function getFortyFive(){
        $start =  date("Y-m-d H:i:s",strtotime("+45 day"));
        return $start;
//       return [now(),$start];
    }
    public function store(RecognizeDrivingLicense $license,Request $request){
        $car = $license->where('plate_number',$request->plate_number)->where('deleted_at',null)->first();
        if($car){
            return $this->failed('车牌号不能重复',201);
        }
        $data = $request->all();
        if($request->total_mileage<$request->last_maintenance_mileage){
            return $this->failed('保养公里数不能大于当前公里数',201);
        }
        $data['last_mileage'] = $request->total_mileage-$request->last_maintenance_mileage+$request->mileage??0;
        $license->fill($data);
        $license->save();
        // 新增成功后，返回新增的车辆信息
        return $this->success($license);
    }
    public function edit(RecognizeDrivingLicense $license,Request $request){
        if ($request->filled('onlydetail')) {
            $data = $license->find($request->id);
            return $this->success($data);
        } else {
            $data = $license
                ->with('carSeries','carCost','insuranceLog')
                ->with(['waittingService'=>function($query){
                    $query->select('id','is_custom','car_id','status','outage_rate','outage_cost','need_start','order_sn')->whereIn('status',[2,3]);
                },'carSeries'])
                ->select('cars.id as car_id','cars.name as car_name','cars.base_price as car_base_price','cars.brokerage as car_brokerage','cars.minimum_price as car_minimum_price','recognize_driving_licenses.*')
                ->join('cars','recognize_driving_licenses.car_series_id','=','cars.id')
                ->find($request->id);
            return $this->success($data);
        }
    }
    public function update(RecognizeDrivingLicense $license,Request $request){
        $array = $request->all();
        $data = $license->find($request->id);

        if($request->filled('mileage')){

            $array['last_mileage'] = $data->total_mileage-$data->last_maintenance_mileage+$request->mileage;
        }
        $data->update($array);
        return $this->success('修改成功');
    }
    //删除
    public function destory(RecognizeDrivingLicense $license,Request $request){
        $data = $license->find($request->id);
        $data->last_price = $request->last_price;
        $data->last_mark = $request->last_mark;
        $data->deleted_at = now();
        $data->save();
        return $this->success('删除成功');
    }
//    删除列表
    public function deleteList(RecognizeDrivingLicense $model,Request $request){
        $size = $request->input('size',10);
        $model = $model->query()->onlyTrashed();
        if($request->filled('search')){
            $model = $model->where(function($query)use($request){
                $query->where('category','like','%'.$request->search.'%')
                    ->orWhere('gear_car_name','like','%'.$request->search.'%')
                    ->orWhere('plate_number','like','%'.$request->search.'%');
            });
        }
        $data = $model->orderBy('deleted_at','desc')->paginate($size);
        return $this->success($data);
    }
    // 处置车辆购置价，历史保险总金额，维保总金额，历史租金收入，再统计盈余金额
    public function deleteCarDetail(RecognizeDrivingLicense $model,Request $request){
        // 车辆订单-已入账的
        $orderlist = CarOrder::query()->whereNotNull('ok_reconciliation_time')->where('plate_number',$request->plate_number)->get();
        // 车辆维修单-已完成的
        $wxlist = Service::query()->where('status',4)->where('plate_number',$request->plate_number)->get();
        // 车辆保养单-已完成的
        $bylist = Maintenance::query()->whereNotNull('end')->where('plate_number',$request->plate_number)->get();
        // 车辆购置价信息
        $costinfo = CarCost::query()->where('car_id',$request->car_id)->first();
        // 车辆保险信息
        $insurelist = InsureLogs::query()->where('car_id',$request->car_id)->get();
        return $this->success(compact('orderlist','wxlist','bylist','costinfo','insurelist'));
    }
    //车辆临时下架
    public function tempFinish(RecognizeDrivingLicense $license,Request $request){
        $data = $license->find($request->id);
        if(!$data){
            return $this->failed('车辆不存在',201);
        }
        $data->temp_finish = 2;
        $data->save();
        return $this->success('临时下架成功');
    }
}
